package cn.com.connected.base.utils;

import cn.com.connected.base.exception.BusinessException;
import cn.com.connected.base.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

@Slf4j
@Component
public class AESUtils {
 
    private static SecretKeySpec secretKey;

    private static String privateKey;

    @Value("${connected.encrypt.secret:#{null}}")
    public void setPrivateKey(String privateKey) {
        AESUtils.privateKey = privateKey;
    }


    public static void setKey(String myKey) throws NoSuchAlgorithmException {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        secretKey = new SecretKeySpec(myKey.getBytes(), "AES");
    }


    public static String encrypt(String strToEncrypt){
        return AESUtils.encrypt(strToEncrypt,privateKey);
    }

    public static String encrypt(String strToEncrypt, String secret){
        try{
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        }catch (Exception e) {
            log.error("Error while encrypting: {}", e.toString());
            throw new BusinessException(ErrorCode.SYSTEM_FAIL);
        }
    }

    public static String decrypt(String strToDecrypt){
        return AESUtils.decrypt(strToDecrypt,privateKey);
    }

    public static String decrypt(String strToDecrypt, String secret){
        try{
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        }catch (Exception e){
            log.error("Error while decrypting: {}",e.toString());
            throw new BusinessException(ErrorCode.SYSTEM_FAIL);
        }
    }
}